import 'package:flutter/material.dart';
import '../models/fishing_technique.dart';
import '../models/comment.dart';
import '../services/technique_service.dart';

class TechniqueProvider with ChangeNotifier {
  final TechniqueService _techniqueService = TechniqueService();
  
  List<FishingTechnique> _techniques = [];
  FishingTechnique? _currentTechnique;
  List<Comment> _comments = [];
  bool _isLoading = false;
  bool _isLoadingComments = false;
  String _error = '';
  int _currentPage = 1;
  int _totalCount = 0;
  bool _hasMore = true;

  List<FishingTechnique> get techniques => _techniques;
  FishingTechnique? get currentTechnique => _currentTechnique;
  List<Comment> get comments => _comments;
  bool get isLoading => _isLoading;
  bool get isLoadingComments => _isLoadingComments;
  String get error => _error;
  bool get hasMore => _hasMore;

  // 根据分类和难度筛选钓技
  List<FishingTechnique> getFilteredTechniques(String category, String difficulty, String searchQuery) {
    var filtered = _techniques;

    // 按分类筛选
    if (category != '全部') {
      filtered = filtered.where((technique) => technique.category == category).toList();
    }

    // 按难度筛选
    if (difficulty != 'all') {
      filtered = filtered.where((technique) => technique.difficulty == difficulty).toList();
    }

    // 按搜索关键词筛选
    if (searchQuery.isNotEmpty) {
      filtered = filtered.where((technique) => 
        technique.title.toLowerCase().contains(searchQuery.toLowerCase()) ||
        technique.subtitle.toLowerCase().contains(searchQuery.toLowerCase()) ||
        technique.tags.any((tag) => tag.toLowerCase().contains(searchQuery.toLowerCase()))
      ).toList();
    }

    return filtered;
  }

  // 加载钓技列表
  Future<void> loadTechniques({
    String? category,
    String? difficulty,
    String? searchQuery,
    bool refresh = false,
  }) async {
    if (refresh) {
      _currentPage = 1;
      _hasMore = true;
      _techniques.clear();
    }

    if (!_hasMore || _isLoading) return;

    _isLoading = true;
    _error = '';
    notifyListeners();

    try {
      final result = await _techniqueService.getTechniqueList(
        pageNum: _currentPage,
        pageSize: 10,
        title: searchQuery,
        category: category,
        difficulty: difficulty,
      );

      final List<FishingTechnique> newTechniques = result['techniques'];
      _totalCount = result['total'];

      if (refresh) {
        _techniques = newTechniques;
      } else {
        _techniques.addAll(newTechniques);
      }

      _currentPage++;
      _hasMore = _techniques.length < _totalCount;
      _error = '';
    } catch (e) {
      _error = '加载失败：$e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 点赞/取消点赞文章
  Future<void> toggleLike(String id) async {
    try {
      final result = await _techniqueService.toggleLike(id);
      
      // 更新当前文章的点赞状态
      if (_currentTechnique != null && _currentTechnique!.id.toString() == id) {
        _currentTechnique = FishingTechnique(
          id: _currentTechnique!.id,
          title: _currentTechnique!.title,
          subtitle: _currentTechnique!.subtitle,
          content: _currentTechnique!.content,
          imageUrl: _currentTechnique!.imageUrl,
          category: _currentTechnique!.category,
          difficulty: _currentTechnique!.difficulty,
          readCount: _currentTechnique!.readCount,
          likeCount: result['likeCount'],
          favoriteCount: _currentTechnique!.favoriteCount,
          commentCount: _currentTechnique!.commentCount,
          tags: _currentTechnique!.tags,
          author: _currentTechnique!.author,
          createTime: _currentTechnique!.createTime,
          estimatedReadTime: _currentTechnique!.estimatedReadTime,
          isLiked: result['isLiked'],
          isFavorited: _currentTechnique!.isFavorited,
          favoriteTime: _currentTechnique!.favoriteTime,
        );
      }
      
      // 同时更新列表中的对应文章
      final listIndex = _techniques.indexWhere((tech) => tech.id.toString() == id);
      if (listIndex != -1) {
        _techniques[listIndex] = FishingTechnique(
          id: _techniques[listIndex].id,
          title: _techniques[listIndex].title,
          subtitle: _techniques[listIndex].subtitle,
          content: _techniques[listIndex].content,
          imageUrl: _techniques[listIndex].imageUrl,
          category: _techniques[listIndex].category,
          difficulty: _techniques[listIndex].difficulty,
          readCount: _techniques[listIndex].readCount,
          likeCount: result['likeCount'],
          favoriteCount: _techniques[listIndex].favoriteCount,
          commentCount: _techniques[listIndex].commentCount,
          tags: _techniques[listIndex].tags,
          author: _techniques[listIndex].author,
          createTime: _techniques[listIndex].createTime,
          estimatedReadTime: _techniques[listIndex].estimatedReadTime,
          isLiked: result['isLiked'],
          isFavorited: _techniques[listIndex].isFavorited,
          favoriteTime: _techniques[listIndex].favoriteTime,
        );
      }
      
      notifyListeners();
    } catch (e) {
      _error = '点赞操作失败：$e';
      notifyListeners();
    }
  }

  // 收藏/取消收藏文章
  Future<void> toggleFavorite(String id) async {
    try {
      final result = await _techniqueService.toggleFavorite(id);
      
      // 更新当前文章的收藏状态
      if (_currentTechnique != null && _currentTechnique!.id.toString() == id) {
        _currentTechnique = FishingTechnique(
          id: _currentTechnique!.id,
          title: _currentTechnique!.title,
          subtitle: _currentTechnique!.subtitle,
          content: _currentTechnique!.content,
          imageUrl: _currentTechnique!.imageUrl,
          category: _currentTechnique!.category,
          difficulty: _currentTechnique!.difficulty,
          readCount: _currentTechnique!.readCount,
          likeCount: _currentTechnique!.likeCount,
          favoriteCount: result['favoriteCount'],
          commentCount: _currentTechnique!.commentCount,
          tags: _currentTechnique!.tags,
          author: _currentTechnique!.author,
          createTime: _currentTechnique!.createTime,
          estimatedReadTime: _currentTechnique!.estimatedReadTime,
          isLiked: _currentTechnique!.isLiked,
          isFavorited: result['isFavorited'],
          favoriteTime: _currentTechnique!.favoriteTime,
        );
      }
      
      // 同时更新列表中的对应文章
      final listIndex = _techniques.indexWhere((tech) => tech.id.toString() == id);
      if (listIndex != -1) {
        _techniques[listIndex] = FishingTechnique(
          id: _techniques[listIndex].id,
          title: _techniques[listIndex].title,
          subtitle: _techniques[listIndex].subtitle,
          content: _techniques[listIndex].content,
          imageUrl: _techniques[listIndex].imageUrl,
          category: _techniques[listIndex].category,
          difficulty: _techniques[listIndex].difficulty,
          readCount: _techniques[listIndex].readCount,
          likeCount: _techniques[listIndex].likeCount,
          favoriteCount: result['favoriteCount'],
          commentCount: _techniques[listIndex].commentCount,
          tags: _techniques[listIndex].tags,
          author: _techniques[listIndex].author,
          createTime: _techniques[listIndex].createTime,
          estimatedReadTime: _techniques[listIndex].estimatedReadTime,
          isLiked: _techniques[listIndex].isLiked,
          isFavorited: result['isFavorited'],
          favoriteTime: _techniques[listIndex].favoriteTime,
        );
      }
      
      notifyListeners();
    } catch (e) {
      _error = '收藏操作失败：$e';
      notifyListeners();
    }
  }

  // 加载评论列表
  Future<void> loadComments(String techniqueId, {bool refresh = false}) async {
    if (refresh) {
      _comments.clear();
    }

    _isLoadingComments = true;
    notifyListeners();

    try {
      final result = await _techniqueService.getComments(techniqueId);
      _comments = result['comments'];
    } catch (e) {
      _error = '加载评论失败：$e';
    } finally {
      _isLoadingComments = false;
      notifyListeners();
    }
  }

  // 发表评论
  Future<void> addComment(String techniqueId, String content, {String? parentId}) async {
    try {
      final result = await _techniqueService.addComment(techniqueId, content, parentId: parentId);
      
      if (result['success'] == true) {
        // 重新加载评论列表以获取最新数据
        await loadComments(techniqueId, refresh: true);
        
        // 更新评论数
        if (_currentTechnique != null) {
          _currentTechnique = FishingTechnique(
            id: _currentTechnique!.id,
            title: _currentTechnique!.title,
            subtitle: _currentTechnique!.subtitle,
            content: _currentTechnique!.content,
            imageUrl: _currentTechnique!.imageUrl,
            category: _currentTechnique!.category,
            difficulty: _currentTechnique!.difficulty,
            readCount: _currentTechnique!.readCount,
            likeCount: _currentTechnique!.likeCount,
            favoriteCount: _currentTechnique!.favoriteCount,
            commentCount: _currentTechnique!.commentCount + 1,
            tags: _currentTechnique!.tags,
            author: _currentTechnique!.author,
            createTime: _currentTechnique!.createTime,
            estimatedReadTime: _currentTechnique!.estimatedReadTime,
            isLiked: _currentTechnique!.isLiked,
            isFavorited: _currentTechnique!.isFavorited,
            favoriteTime: _currentTechnique!.favoriteTime,
          );
        }
      } else {
        _error = result['message'] ?? '发表评论失败';
      }
      
      notifyListeners();
    } catch (e) {
      _error = '发表评论失败：$e';
      notifyListeners();
    }
  }

  // 点赞/取消点赞评论
  Future<void> toggleCommentLike(String commentId) async {
    try {
      final result = await _techniqueService.toggleCommentLike(commentId);
      
      // 更新评论列表中的点赞状态
      final index = _comments.indexWhere((comment) => comment.id.toString() == commentId);
      if (index != -1) {
        _comments[index] = _comments[index].copyWith(
          likeCount: result['likeCount'],
          isLiked: result['isLiked'],
        );
        notifyListeners();
      }
    } catch (e) {
      _error = '评论点赞操作失败：$e';
      notifyListeners();
    }
  }

  // 加载钓技详情
  Future<void> loadTechniqueDetail(String id) async {
    _isLoading = true;
    _error = '';
    notifyListeners();

    try {
      _currentTechnique = await _techniqueService.getTechniqueDetail(id);
      
      // 增加阅读量
      await _techniqueService.incrementReadCount(id);
      
      _error = '';
    } catch (e) {
      _error = '加载详情失败：$e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 点赞钓技
  Future<void> likeTechnique(int id) async {
    try {
      final index = _techniques.indexWhere((technique) => technique.id == id);
      if (index != -1) {
        // 这里应该调用API更新点赞数
        // 暂时只在本地更新
        notifyListeners();
      }
    } catch (e) {
      _error = '点赞失败: $e';
      notifyListeners();
    }
  }

  // 收藏钓技
  Future<void> favoriteTechnique(int id) async {
    try {
      // 这里应该调用API添加收藏
      notifyListeners();
    } catch (e) {
      _error = '收藏失败: $e';
      notifyListeners();
    }
  }

}